package com.wujie.springjdbctemplate.dao.impl;

import com.wujie.springjdbctemplate.dao.StudentDao;
import com.wujie.springjdbctemplate.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class StudentDaoImpl implements StudentDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public int add(Student student) {
        return jdbcTemplate.update("insert into student(name, age) values(?, ?)",student.getName(),student.getAge());
    }

    @Override
    public int update(Student student) {
        return jdbcTemplate.update("update student set name = ?,age=? where id=?",student.getName(),student.getAge(),student.getId());
    }

    @Override
    public int delete(Integer id) {
        return jdbcTemplate.update("delete from student where id=?",id);
    }

    @Override
    public Student findStudentById(Integer id) {
        List<Student> list = jdbcTemplate.query("select * from student where id = ?", new Object[]{id}, new BeanPropertyRowMapper<>(Student.class));
        if (list != null && list.size() >0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<Student> findStudent() {
        List<Student> list = jdbcTemplate.query("select * from student", new Object[]{}, new BeanPropertyRowMapper<>(Student.class));
        if (list != null && list.size() >0) {
            return list;
        }
        return null;
    }
}
